import {getAuthToken} from "@/utils/auth";
import {message} from "antd";
import {correspVal} from "@/utils/biz";
import * as API from "@/services";
import queryString from "query-string";

export const triggerDownload = (url: string) => {
  const a = document.createElement('a');
  a.href = url;
  document.body.appendChild(a);
  a.click();
  // 清理资源
  document.body.removeChild(a);
}

export const processError = (e: any, isZhCN?: boolean) => {
  if (e.response.status === 404) {
    message.error(correspVal(isZhCN, 'PDF文件不存在', 'PDF file does not exist'));
    return;
  } else if (e.status === 402) {
    message.error(correspVal(isZhCN, '您未订阅指定的刊期', 'You have not subscribed to the specified issue.'));
    return;
  } else if (e.response?.data?.msg) {
    message.error(e.response?.data?.msg)
  } else {
    message.error('下载失败');
  }
}

export const downloadJournalPeriodPdf = async (period?: API.FrontJournalPeriod, isZhCN?: boolean) => {
  try {
    if (!period) {
      return;
    }
    const resp = await API.preCheckJournalPeriodDownload(period.id, {skipErrorHandler: true});
    if (resp.flag) {
      const journalName = ((correspVal(isZhCN, `《${period.journal.journalNameCn}》`, period.journal.journalNickname || period.journal.journalNameEn) || period.journal.journalNickname) || "").replace(/\s/g, '_');
      const fname = `${journalName}${period?.year}_${period?.volume}(${period?.period}).pdf`
      const searchString = queryString.stringify({
        authToken: getAuthToken(),
        fname
      })
      const url = `${REQUEST_BASE_URL}/api/v1/front/journal-period/${period?.id}/pdf?${searchString}`;
      triggerDownload(url)
    }
  } catch (e: any) {
    processError(e, isZhCN);
  }
}
